import React, { Component } from 'react'
import { connect } from 'react-redux'
import ReactLoading from 'react-loading'
import { global as globalDuck } from 'ducks'
import { push } from 'connected-react-router'
import Zhiqing from 'icons/zhiqing.png'
import Lock from './auth0'

class Auth extends Component {
  componentDidMount() {
    const {
      location, match, actionReciveUser, link, actionAuthed, actionSetReturnUrl,
    } = this.props
    if (location.state && location.state.returnURL) {
      actionSetReturnUrl(location.state.returnURL)
    }
    Lock.checkSession({}, (err, authResult) => {
      // handle error or new tokens
      console.log('&&&&&&&&&&&&&&&', err, authResult)
      if (err) {
        let redirectURL
        if (location.state && location.state.returnURL) {
          redirectURL = location.state.returnURL
        }
        if (redirectURL) {
          localStorage.setItem('redirectURL', redirectURL)
        }
        link('/sign-in')
      }
      if (authResult && authResult.accessToken && authResult.idToken) {
        localStorage.setItem('token', authResult.idToken)
        if (authResult.idTokenPayload) {
          actionAuthed(authResult.idTokenPayload)
        }
        // Lock.getUserInfo(authResult.accessToken, (error, profile) => {
        //   if (error) {
        //     // Handle error
        //     console.log('auth error: ', error)
        //     return
        //   }
        //   // Store the token from authResult for later use
        //   actionReciveUser(profile)

        //   let redirectURL
        //   if (location.state && location.state.returnURL) {
        //     redirectURL = location.state.returnURL
        //   }

        //   const localUrl = localStorage.getItem('redirectURL')

        //   if (redirectURL) {
        //     link(redirectURL)
        //   } else if (localUrl) {
        //     localStorage.removeItem('redirectURL')
        //     link(localUrl)
        //   } else {
        //     link('/')
        //   }
        // })
      }
    })
  }

  render() {
    return (
      <div className="page-loading">
        <img src={Zhiqing} style={{ height: '100px' }} alt="" />
        <ReactLoading color="#000000" height={100} width={100} type="bars" />
      </div>
    )
  }
}

const mapDispatchToProps = {
  actionReciveUser: globalDuck.creators.actionReciveUser,
  actionSetReturnUrl: globalDuck.creators.actionSetReturnUrl,
  actionAuthed: globalDuck.creators.actionAuthed,
  link: path => push(path),
}

export default connect(
  null,
  mapDispatchToProps,
)(Auth)
